import os
import docx
import jieba as jb
import pandas as pd
from collections import Counter
import wordcloud

def load_document(file_path):
    if not os.path.isfile(file_path):
        raise FileNotFoundError(f"The file {file_path} does not exist.")
    return docx.Document(file_path)

def process_text(paragraphs):
    result = []
    for text in paragraphs:
        process = list(jb.cut(text.text))
        result.extend(process)
    return result

def count_words(word_list):
    return Counter(word_list)

def generate_wordcloud(word_list, excludes, output_file):
    data = ' '.join(word for word in word_list if word not in excludes)
    wc = wordcloud.WordCloud(font_path='simhei.ttf', background_color="white", 
                             width=800, height=600, max_words=100, 
                             max_font_size=80, stopwords=set(excludes))
    wc.generate(data)
    wc.to_file(output_file)

def main():
    try:
        file_path = input("请输入文件路径: ")
        doc = load_document(file_path)
        words = process_text(doc.paragraphs)
        word_counts = count_words(words)
        series = pd.Series(word_counts).sort_values(ascending=False)
        
        pd.set_option("display.max_rows", None)
        pd.set_option("display.max_columns", None)
        pd.set_option("display.width", None)
        
        excludes = ['。', '，', '“', '”', '→']
        generate_wordcloud(words, excludes, 'result.jpg')
        print(series)
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    main()